<template>
	<view>
		<headerVue transparent="1" title="RGB转16进制" />
		<view class="tip">输入数字范围 0 ~ 255</view>
		<view class="flex-wrap">
			<input type="number" @blur="checkNum('red')" v-model="colorObj.red" placeholder="红色">
			<input type="number" @blur="checkNum('green')" v-model="colorObj.green" placeholder="绿色">
			<input type="number" @blur="checkNum('blue')" v-model="colorObj.blue" placeholder="蓝色">
		</view>
		
		<button class="btn" @click="rgbToHex">转换成16进制</button>
		
		<view class="result" v-if="result">
			{{ result }}
			<view class="color" :style="{backgroundColor: result}"></view>
			<text @tap="copy">复制</text>
		</view>
	</view>
</template>

<script>
	import headerVue from '../../components/header.vue';
	export default {
		components:{
			headerVue
		},
		data(){
			return {
				colorObj: {
					red: 0,
					green: 0,
					blue: 0
				},
				result: undefined
			}
		},
		methods:{
			checkNum(type){
				this.colorObj[type] = parseInt(this.colorObj[type])
				if (this.colorObj[type] < 0 || isNaN(this.colorObj[type])){
					this.colorObj[type] = 0
				} else if (this.colorObj[type] > 255) {
					this.colorObj[type] = 255
				}
			},
			rgbToHex(r, g, b) {
			    // 确保输入值在0-255范围内
			    const red = this.colorObj.red;
			    const green = this.colorObj.green;
			    const blue = this.colorObj.blue;
			    
			    // 将每个值转换为两位十六进制数
			    const hexR = red.toString(16).padStart(2, '0');
			    const hexG = green.toString(16).padStart(2, '0');
			    const hexB = blue.toString(16).padStart(2, '0');
			    // 组合并返回带#的十六进制颜色
			    this.result = `#${hexR}${hexG}${hexB}`.toUpperCase();
			},
			copy(){
				uni.setClipboardData({
					data: this.result, // 要复制的文字内容
					success: () => {
						// 复制成功提示
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						// 复制失败提示
						uni.showToast({
							title: '复制失败，请重试',
							icon: 'none'
						});
						console.error('复制失败：', err);
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tip{
		margin: 64rpx 24rpx 24rpx;
		color: #333;
	}

	.result{
		text-align: center;
		margin-top: 24rpx;
		.color{
			margin-left: 12rpx;
			display: inline-block;
			width: 40rpx;
			height: 40rpx;
			border-radius: 8rpx;
			vertical-align: -10rpx;
		}
		text{
			padding-left: 32rpx;
			color: #39c5bb;
		}
	}
	.flex-wrap{
		margin: 40rpx auto;
		width: 90%;
		display: flex;
		gap: 20rpx;
		input{
			padding: 12rpx;
			text-align: center;
			border-radius: 16rpx;
			border: 1rpx solid #e0e0e0;
		}
	}
</style>